//
//  NSString+Scale.m
//  K8_2
//
//  Created by Damon on 15/7/21.
//  Copyright (c) 2015年 imac. All rights reserved.
//

#import "NSString+Scale.h"

@implementation NSString (Scale)

- (NSString *)stringWithScale:(NSInteger)scale
{
    NSMutableString *str = [NSMutableString stringWithString:self];
    NSRange range = [self rangeOfString:@"."];
    if (range.location != NSNotFound )
    {
        if (scale > 0)
        {
            if (str.length >= (range.location + range.length + scale))
            {
                [str setString:[self substringWithRange:NSMakeRange(0, range.location + range.length + scale)]];
            }
            else
            {
                for (NSInteger i = 0; i < scale - (str.length - range.location - range.length); i++)
                {
                    [str appendString:@"0"];
                }
            }
        }
        else
        {
            if (str.length >= range.location + range.length + scale)
            {
                [str setString:[self substringWithRange:NSMakeRange(0, range.location)]];
            }
        }
    }
    else
    {
        if (scale == 0)
        {
            return self;
        }
        else
        {
            [str appendString:@"."];
            for (NSInteger i = 0; i < scale; i++)
            {
                [str appendString:@"0"];
            }
        }
    }
    return str;
}

- (NSInteger)scaleOfString
{
    NSRange range = [self rangeOfString:@"."];
    if (range.location != NSNotFound)
    {
        return (self.length - range.location - 1);
    }
    else
    {
        return 0;
    }
}

- (CGFloat)floatWithScale:(NSInteger)scale
{
    CGFloat floatVaule = [self floatValue];
    NSInteger powScale = pow(10, scale);
    floatVaule = floatVaule * powScale;
    int floatInt = (int)floatVaule;
    return floatInt / powScale;
}

- (NSString *)betterString
{
    NSRange range = [self rangeOfString:@"."];
    if (range.location == NSNotFound)
    {
        return self;
    }
    NSInteger start;
    for (NSInteger i = self.length - 1; i >= 0; i--)
    {
        unichar a = [self characterAtIndex:i];
        if (a != '0')
        {
            start = (range.location == i) ? i : i + 1;
            break;
        }
    }
    NSString *string = [self substringWithRange:NSMakeRange(0, start)];
    return string;
}

- (NSString *)strNumberByScale:(NSInteger)scale
{
    double number = round(self.doubleValue * pow(10, scale)) / pow(10, scale);
    return [[NSString stringWithFormat:@"%lf", number] stringWithScale:scale];
}
@end
